local extension = Package("ling8")
extension.extensionName = "lingling"

local U = require "packages/utility/utility"

local getNearBy = function (player)
  return {player:getLastAlive().id, player:getNextAlive().id}
end

local zhuyuanzhang = General(extension, "lingling__zhuyuanzhang", "ming", 4)
local zilei = fk.CreateTriggerSkill{
  name = "lingling__zilei",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.TurnEnd, fk.TargetConfirmed, fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.TurnEnd then
        return target == player
      elseif event == fk.TargetConfirmed then
        return target == player and data.from ~= player.id and data.card.is_damage_card
      elseif event == fk.CardUseFinished then
        return target ~= player and data.card.is_damage_card and data.damageDealt and data.damageDealt[player.id] and
          table.contains(TargetGroup:getRealTargets(data.tos), player.id)
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event == fk.TurnEnd then
      room:notifySkillInvoked(player, self.name, "negative")
      room:askForDiscard(player, 2, 2, false, self.name, false)
    else
      room:notifySkillInvoked(player, self.name, "drawcard")
      local n = player:isKongcheng() and 2 or 1
      if event == fk.CardUseFinished then
        n = 1
      end
      player:drawCards(n, self.name)
    end
  end
}
local xiongyi = fk.CreateTriggerSkill{
  name = "lingling__xiongyi",
  anim_type = "big",
  events = {fk.RoundStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and player.room:getTag("RoundCount") == 8
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local to = room:askForChoosePlayers(player, {player:getNextAlive().id, player:getLastAlive().id}, 1, 1,
      "#lingling__xiongyi-choose", self.name, true)
    if #to > 0 then
      self.cost_data = {tos = to}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:damage{
      from = player,
      to = room:getPlayerById(self.cost_data.tos[1]),
      damage = 3,
    }
  end,
}
zhuyuanzhang:addSkill(zilei)
zhuyuanzhang:addSkill(xiongyi)
Fk:loadTranslationTable{
  ["lingling__zhuyuanzhang"] = "朱元璋",
  ["#lingling__zhuyuanzhang"] = "洪武太祖",
  ["designer:lingling__zhuyuanzhang"] = "伶",
  ["illustrator:lingling__zhuyuanzhang"] = "珊瑚虫",
  ["lingling__zilei"] = "自累",
  [":lingling__zilei"] = "回合结束时，你弃置两张手牌。当其他角色使用伤害类牌指定你为目标后，你摸一张牌，若你没有手牌则额外摸一张牌，"..
  "若此牌对你造成伤害，则再摸一张牌。",
  ["lingling__xiongyi"] = "凶疑",
  [":lingling__xiongyi"] = "第八轮及之后每轮开始时，你可以对一名邻家造成3点伤害。"..
  "<br><br> <font color='#a40000'>杀尽江南百万兵，腰间宝剑犹血腥。</font>",
  ["#lingling__xiongyi-choose"] = "凶疑：你可以对一名相邻角色造成3点伤害！",

  ["$lingling__xiongyi1"] = "藏兵匿甲，坐罪九族！",
  ["$lingling__xiongyi2"] = "结党营私，扒皮实草！",
}

local zhudi = General(extension, "lingling__zhudi", "ming", 4)
local zhengbian = fk.CreateActiveSkill{
  name = "lingling__zhengbian",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__zhengbian",
  can_use = Util.TrueFunc,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    local to = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and (Self:getLastAlive() == to or Self:getNextAlive() == to)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:handleAddLoseSkills(player, "-lingling__zhengbian", nil, true, false)
    if not target.dead and not target:hasSkill(self, true) then
      room:handleAddLoseSkills(target, "lingling__zhengbian", nil, true, false)
    end
    if not target.dead then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
    end
  end,

  on_lose = function (self, player, is_death)
    if is_death then
      local room = player.room
      for _, p in ipairs(room:getAlivePlayers()) do
        if (p.general == "lingling__zhudi" or p.deputyGeneral == "lingling__zhudi") and not p:hasSkill(self, true) then
          room:handleAddLoseSkills(p, "lingling__zhengbian", nil, true, false)
        end
      end
    end
  end,
}
local huantu = fk.CreateTriggerSkill{
  name = "lingling__huantu",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.Damaged},
  on_trigger = function(self, event, target, player, data)
    self.cancel_cost = false
    for i = 1, data.damage do
      if i > 1 and (self.cancel_cost or not player:hasSkill(self)) then return false end
      self:doCost(event, target, player, data)
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = player
    if player:usedSkillTimes("lingling__jingnan", Player.HistoryGame) == 0 then
      to = room:askForChoosePlayers(player, {player:getNextAlive().id, player:getLastAlive().id}, 1, 1,
        "#lingling__huantu-choose", self.name, false)
      to = room:getPlayerById(to[1])
    end
    local choice = room:askForChoice(to, {"basic", "trick", "equip"}, self.name, "#lingling__huantu-choice:" .. player.id)
    room:sendLog{
      type = "#HuantuDeclareType",
      from = to.id,
      arg = choice,
    }
    local n = player:usedSkillTimes("lingling__jingnan", Player.HistoryGame) > 0 and 2 or 1
    local cid = room:getCardsFromPileByRule(".|.|.|.|.|"..choice, n, "allPiles")
    if #cid > 0 then
      if player:hasSkill("lingling__jingnan", true) and player:usedSkillTimes("lingling__jingnan", Player.HistoryGame) == 0 then
        room:addPlayerMark(player, "@lingling__jingnan_record", 1)
      end
      room:obtainCard(player, cid, false, fk.ReasonJustMove, nil, self.name )
    end
  end,
}
local jingnan = fk.CreateTriggerSkill{
  name = "lingling__jingnan",
  frequency = Skill.Wake,
  events = {fk.AfterSkillEffect},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.name == "lingling__huantu" and
      player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  can_wake = function (self, event, target, player, data)
    return player:getMark("@lingling__jingnan_record") > 2
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@lingling__jingnan_record", 0)
    room:changeMaxHp(player, -1)
    if player.dead then return end
    if not player:isWounded() then
      player:drawCards(2, self.name)
    else
      local choices = {"draw2", "recover"}
      local choice = room:askForChoice(player, choices, self.name)
      if choice == "recover" then
        room:recover{
          who = player,
          num = 1,
          skillName = self.name
        }
      else
        player:drawCards(2, self.name)
      end
    end
    if player.dead then return end
    room:handleAddLoseSkills(player, "lingling__yongle")
  end,
}
local yongle = fk.CreateViewAsSkill{
  name = "lingling__yongle",
  anim_type = "special",
  pattern = ".",
  prompt = "#lingling__yongle",
  interaction = function(self)
    local all_names = U.getAllCardNames("bt")
    local names = U.getViewAsCardNames(Self, self.name, all_names)
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    if not self.interaction.data or #selected > 1 then return end
    local type = Fk:cloneCard(self.interaction.data).type
    if Fk:getCardById(to_select).type ~= type then
      if #selected == 0 then
        return true
      else
        return Fk:getCardById(to_select).type ~= Fk:getCardById(selected[1]).type
      end
    end
  end,
  view_as = function(self, cards)
    if not self.interaction.data or #cards ~= 2 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,
  enabled_at_play = Util.TrueFunc,
  enabled_at_response = function(self, player, response)
    return not response
  end,
}
zhudi:addSkill(zhengbian)
zhudi:addSkill(huantu)
zhudi:addSkill(jingnan)
zhudi:addRelatedSkill(yongle)
Fk:loadTranslationTable{
  ["lingling__zhudi"] = "朱棣",
  ["#lingling__zhudi"] = "永乐大帝",
  ["designer:lingling__zhudi"] = "伶",
  ["illustrator:lingling__zhudi"] = "珊瑚虫",
  ["lingling__zhengbian"] = "征边",
  [":lingling__zhengbian"] = "出牌阶段，你可以失去此技能，令上家或下家获得此技能，然后对其造成1点伤害。你死亡时，朱棣获得此技能。",
  ["lingling__huantu"] = "缓图",
  [":lingling__huantu"] = "当你受到1点伤害后，你从牌堆获得一张由你指定的邻家声明类型的牌。",
  ["lingling__jingnan"] = "靖难",
  [":lingling__jingnan"] = "觉醒技，当你因〖缓图〗累计获得三张牌后，你减1点体力上限，回复1点体力或摸两张牌，〖缓图〗改为由你声明类型且"..
  "描述中的“一张”改为“两张”，然后获得〖永乐〗。",
  ["lingling__yongle"] = "永乐",
  [":lingling__yongle"] = "你可以将两张类型不同的牌当另一种类型的任意牌使用（不能当装备牌和延时锦囊牌）。"..
  "<br><br> <font color='#a40000'>洪武、永乐所行之事，远迈前王。</font>",
  ["#lingling__zhengbian"] = "征边：你可以对上家或下家造成1点伤害，你失去此技能，其获得此技能",
  ["#lingling__huantu-choose"] = "缓图：你可以选择一名邻家，其声明一种类型并令你获得一张该类型的牌",
  ["#lingling__huantu-choice"] = "缓图：%src 令你声明一种类别，令其获得此类别的牌",
  ["#HuantuDeclareType"] = "%from 声明了 %arg",
  ["@lingling__jingnan_record"] = "靖难",
  ["#lingling__yongle"] = "永乐：将两张类型不同的牌当另一种类型的牌使用",

  ["$lingling__jingnan"] = "过家家的游戏就到此为止吧。",
}

local liuji = General(extension, "lingling__liuji", "ming", 3)
local tuibei = fk.CreateActiveSkill{
  name = "lingling__tuibei",
  anim_type = "offensive",
  target_filter = Util.FalseFunc,
  card_filter = Util.FalseFunc,
  can_use = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and player:getMark("lingling__tuibei_count-turn") < 4
  end,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    while true do
      if player:getMark("lingling__tuibei_count-turn") > 3 then return end
      if player.dead then return end
      local id = room:getNCards(1, "bottom")[1]
      room:moveCards({
        ids = {id},
        toArea = Card.Processing,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
        proposer = player.id,
      })
      local use = U.askForUseRealCard(room, player, {id}, ".", self.name, "#lingling__tuibei-use:::" .. Fk:getCardById(id, true):toLogString(), {expand_pile = {id}, bypass_times = true}, true)
      if use then
        room:addPlayerMark(player, "lingling__tuibei_count-turn", 1)
        room:useCard(use)
      else
        room:delay(800)
        room:moveCards({
          ids = {id},
          fromArea = Card.Processing,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonPutIntoDiscardPile,
        })
        return
      end
    end
  end,
}
local ruliu = fk.CreateTriggerSkill{
  name = "lingling__ruliu",
  anim_type = "special",
  events = {fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) or data.card.type ~= Card.TypeTrick then return end
    if not table.contains(player:getTableMark("@$lingling__ruliu"), data.card.trueName) then
      self.cost_data = 1
      return table.contains(getNearBy(player), target.id) or target == player
    else
      if target == player then
        self.cost_data = 2
        return true
      else
        self.cost_data = 3
        return table.contains(U.getActualUseTargets(player.room, data, event), player.id) and (not data.card:isVirtual() or #(data.card.subcards or {}) > 0)
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if self.cost_data == 1 or self.cost_data == 2 then
      return true
    elseif self.cost_data == 3 then
      return player.room:askForSkillInvoke(player, self.name, nil, "#lingling__ruliu-invoke:::" .. data.card:toLogString())
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if self.cost_data == 1 then
      local mark = player:getTableMark("@$lingling__ruliu")
      table.insertIfNeed(mark, data.card.trueName)
      room:setPlayerMark(player, "@$lingling__ruliu", mark)
    elseif self.cost_data == 2 then
      player:drawCards(2, self.name)
    else
      room:moveCards{
        ids = Card:getIdList(data.card),
        toArea = Card.DrawPile,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
        drawPilePosition = -1,
        moveVisible = true,
      }
      room:sendLog{
        type = "#RuliuPutCardIntoDrawPile",
        from = player.id,
        card = Card:getIdList(data.card),
      }
    end
  end,
}
liuji:addSkill(tuibei)
liuji:addSkill(ruliu)
Fk:loadTranslationTable{
  ["lingling__liuji"] = "刘基",
  ["#lingling__liuji"] = "济时之器",
  ["designer:lingling__liuji"] = "伶",
  ["illustrator:lingling__liuji"] = "珊瑚虫",
  ["lingling__tuibei"] = "推背",
  [":lingling__tuibei"] = "出牌阶段限一次，你可以亮出牌堆底的牌，然后若你能使用此牌则重复此流程（每回合你至多以此法使用四张牌）。",
  ["#lingling__tuibei-use"] = "推背：你可以使用此 %arg",
  ["lingling__ruliu"] = "如流",
  [":lingling__ruliu"] = "当你和你邻家使用你未记录的锦囊牌结算后，你记录此牌。其他角色对你使用你记录的锦囊牌结算后，你可以将之置于牌堆底。你使用你记录的锦囊牌后摸两张牌。"..
  "<br><br> <font color='#a40000'>三分天下诸葛亮，一统江山刘伯温。</font>",
  ["@$lingling__ruliu"] = "如流",
  ["#lingling__ruliu-invoke"] = "如流：你可以将此 %arg 置于牌堆底",
  ["#RuliuPutCardIntoDrawPile"] = "%from 将 %card 置于牌堆底",
}

--[[
local zhenghe = General(extension, "lingling__zhenghe", "ming", 3)
Fk:loadTranslationTable{
  ["lingling__zhenghe"] = "郑和",
  ["#lingling__zhenghe"] = "三宝太监",
  ["designer:lingling__zhenghe"] = "伶",
  ["illustrator:lingling__zhenghe"] = "珊瑚虫",
}

local yuqian = General(extension, "lingling__yuqian", "ming", 3)
Fk:loadTranslationTable{
  ["lingling__yuqian"] = "于谦",
  ["#lingling__yuqian"] = "两袖清风",
  ["designer:lingling__yuqian"] = "伶",
  ["illustrator:lingling__yuqian"] = "珊瑚虫",
}

local wangshouren = General(extension, "lingling__wangshouren", "ming", 3)
Fk:loadTranslationTable{
  ["lingling__wangshouren"] = "王守仁",
  ["#lingling__wangshouren"] = "龙场悟道",
  ["designer:lingling__wangshouren"] = "伶",
  ["illustrator:lingling__wangshouren"] = "珊瑚虫",
}]]

local xuda = General(extension, "lingling__xuda", "ming", 4)
local xuexiong = fk.CreateActiveSkill{
  name = "lingling__xuexiong",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__xuexiong",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    room:askForDiscard(target, 3, 3, true, self.name, false)
    if target.dead then return end
    room:addPlayerMark(target, self.name, 1)
  end
}
local xuexiong_delay = fk.CreateTriggerSkill{
  name = "#lingling__xuexiong_delay",
  anim_type = "drawcard",
  events = {fk.TurnStart, fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:getMark("lingling__xuexiong-turn") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player:drawCards(player:getMark("lingling__xuexiong-turn"), "lingling__xuexiong")
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark("lingling__xuexiong") > 0
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "lingling__xuexiong-turn", player:getMark("lingling__xuexiong"))
    room:setPlayerMark(player, "lingling__xuexiong", 0)
  end,
}
local mochou = fk.CreateTriggerSkill{
  name = "lingling__mochou",
  anim_type = "offensive",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and player:isKongcheng()
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room.alive_players, function (p)
      return player:getNextAlive() == p or player:getLastAlive() == p
    end)
    local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1,
      "#lingling__mochou-choose", self.name, true)
    if #to > 0 then
      self.cost_data = {tos = to}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.tos[1])
    room:damage{
      from = player,
      to = to,
      damage = 1,
      skillName = self.name,
    }
    if to.dead then return end
    local choices = {"lingling__mochou_damage:"..player.id}
    if not player.dead then
      table.insert(choices, 1, "lingling__mochou_draw:"..player.id)
    end
    local choice = room:askForChoice(to, choices, self.name)
    if choice:startsWith("lingling__mochou_damage") then
      room:damage{
        from = player,
        to = to,
        damage = 1,
        skillName = self.name,
      }
    else
      player:drawCards(2, self.name)
    end
  end,
}
xuexiong:addRelatedSkill(xuexiong_delay)
xuda:addSkill(xuexiong)
xuda:addSkill(mochou)
Fk:loadTranslationTable{
  ["lingling__xuda"] = "徐达",
  ["#lingling__xuda"] = "万里长城",
  ["designer:lingling__xuda"] = "伶",
  ["illustrator:lingling__xuda"] = "珊瑚虫",

  ["lingling__xuexiong"] = "削雄",
  [":lingling__xuexiong"] = "出牌阶段限一次，你可以令一名角色弃置三张牌（不足全弃，无牌不弃），其下回合开始时和下回合结束时各摸一张牌。",
  ["lingling__mochou"] = "莫愁",
  [":lingling__mochou"] = "出牌阶段结束时，若你没有手牌，你可以对一名邻家造成1点伤害，然后其选择令你摸两张牌或再受到你造成的1点伤害。"..
  "<br><br> <font color = '#a40000'>百战标奇，六王首功。",
  ["#lingling__xuexiong"] = "削雄：令一名角色弃三张牌，其下回合开始时和下回合结束时各摸一张牌",
  ["#lingling__xuexiong_delay"] = "削雄",
  ["#lingling__mochou-choose"] = "莫愁：你可以对一名邻家造成1点伤害，其选择令你摸两张牌或再受到1点伤害",
  ["lingling__mochou_draw"] = "%src 摸两张牌",
  ["lingling__mochou_damage"] = "%src 再对你造成1点伤害",
}

local zhangjuzheng = General(extension, "lingling__zhangjuzheng", "ming", 3)
local xinzheng = fk.CreateTriggerSkill{
  name = "lingling__xinzheng",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.n < 4
  end,
  on_use = function(self, event, target, player, data)
    data.n = math.min(data.n + 2, 4)
  end,
}
local shengrong = fk.CreateTriggerSkill{
  name = "lingling__shengrong",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseEnd, fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and (player:getNextAlive() == target or target:getNextAlive() == player) then
      local room = player.room
      if event == fk.EventPhaseEnd and target.phase == Player.Discard then
        local cards = {}
        local phase_event = room.logic:getCurrentEvent():findParent(GameEvent.Phase, true)
        if phase_event == nil then return false end
        local end_id = phase_event.id
        room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
          for _, move in ipairs(e.data) do
            if move.from == target.id and move.moveReason == fk.ReasonDiscard then
              for _, info in ipairs(move.moveInfo) do
                if table.contains(room.discard_pile, info.cardId) then
                  table.insertIfNeed(cards, info.cardId)
                end
              end
            end
          end
        end, end_id)
        if #cards > 0 then
          self.cost_data = cards
          return true
        end
      elseif event == fk.CardUseFinished and target.phase == Player.Play and room:getCardArea(data.card) == Card.Processing then
        if #room.logic:getEventsOfScope(GameEvent.UseCard, 5, function (e)
          return e.data[1].from == target.id
        end, Player.HistoryPhase) == 4 then
          self.cost_data = Card:getIdList(data.card)
          return true
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = self.cost_data
    if event == fk.EventPhaseEnd then
      cards = U.askforChooseCardsAndChoice(player, self.cost_data, {"OK"}, self.name, "#lingling__shengrong-prey", {"Cancel"}, 0, 2)
    end
    if #cards > 0 then
      room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
  end,
}
local yitiao = fk.CreateActiveSkill{
  name = "lingling__yitiao",
  anim_type = "special",
  card_num = 3,
  target_num = 0,
  prompt = "#lingling__yitiao",
  can_use = Util.TrueFunc,
  card_filter = function(self, to_select, selected)
    return #selected < 3 and not Self:prohibitDiscard(Fk:getCardById(to_select)) and
      not table.find(selected, function (id)
        return Fk:getCardById(to_select).type == Fk:getCardById(id).type
      end)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:throwCard(effect.cards, self.name, player, player)
    if player.dead then return end
    local all_skills = table.filter(player:getTableMark(self.name), function (s)
      return player:hasSkill(s, true)
    end)
    local skills = {}
    for _, general in pairs(Fk.generals) do
      if not general.hidden and not general.total_hidden then
        table.insertTableIfNeed(skills, general:getSkillNameList(true))
      end
    end
    skills = table.filter(skills, function (s)
      return not player:hasSkill(s, true)
    end)
    if #skills > 0 then
      local skill = table.random(skills)
      table.insert(all_skills, skill)
      room:handleAddLoseSkills(player, skill, nil, true, false)
    end
    if #all_skills > 2 then
      local choice = room:askForChoice(player, all_skills, self.name, "#lingling__yitiao-lose")
      table.removeOne(all_skills, choice)
      room:handleAddLoseSkills(player, "-"..choice, nil, true, false)
    end
    room:setPlayerMark(player, self.name, all_skills)
  end,
}
local yitiao_trigger = fk.CreateTriggerSkill{
  name = "#lingling__yitiao_trigger",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  main_skill = yitiao,
  events = {fk.PreCardEffect},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(yitiao) and data.card.trueName == "supply_shortage" and player.id == data.to
  end,
  on_use = Util.TrueFunc,
}
yitiao:addRelatedSkill(yitiao_trigger)
zhangjuzheng:addSkill(xinzheng)
zhangjuzheng:addSkill(shengrong)
zhangjuzheng:addSkill(yitiao)
Fk:loadTranslationTable{
  ["lingling__zhangjuzheng"] = "张居正",
  ["#lingling__zhangjuzheng"] = "朝下夕行",
  ["designer:lingling__zhangjuzheng"] = "伶",
  ["illustrator:lingling__zhangjuzheng"] = "珊瑚虫",

  ["lingling__xinzheng"] = "新政",
  [":lingling__xinzheng"] = "所有角色摸牌阶段摸牌数+2（至多4）。",
  ["lingling__shengrong"] = "省冗",
  [":lingling__shengrong"] = "你获得邻家弃牌阶段弃置的至多两张牌，和其出牌阶段使用的第四张结算后的实体牌。",
  ["lingling__yitiao"] = "一条",
  [":lingling__yitiao"] = "【兵粮寸断】对你无效。出牌阶段，你可以弃置基本牌、锦囊牌、装备牌各一张，然后随机获得一个技能，以此法获得三个技能后，"..
  "你选择一个以此法获得的技能失去。"..
  "<br><br> <font color = '#a40000'>世间已无张居正。",
  ["#lingling__shengrong-prey"] = "省冗：获得其中至多两张牌",
  ["#lingling__yitiao"] = "一条：弃置每种类别的牌各一张，随机获得一个技能",
  ["#lingling__yitiao-lose"] = "一条：你需失去一个技能",
  ["#lingling__yitiao_trigger"] = "一条",
}

--local lizicheng = General(extension, "lingling__lizicheng", "qun", 4)
Fk:loadTranslationTable{
  ["lingling__lizicheng"] = "李自成",
  ["#lingling__lizicheng"] = "闯王",
  ["designer:lingling__lizicheng"] = "伶",
  ["illustrator:lingling__lizicheng"] = "珊瑚虫",
}

local zhengchenggong = General(extension, "lingling__zhengchenggong", "ming", 4)
local tingzhen = fk.CreateTriggerSkill{
  name = "lingling__tingzhen",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.CardUsing, fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if player.room:getTag("RoundCount") % 2 == 1 then
        return event == fk.CardUsing and data.card.trueName == "slash" and
          #player.room.logic:getEventsOfScope(GameEvent.UseCard, 2, function (e)
            local use = e.data[1]
            return use.from == player.id and use.card.trueName == "slash"
          end, Player.HistoryRound) == 1
      else
        return event == fk.CardUseFinished and data.card.type == Card.TypeTrick and
          #player.room.logic:getEventsOfScope(GameEvent.UseCard, 2, function (e)
            local use = e.data[1]
            return use.from == player.id and use.card.type == Card.TypeTrick
          end, Player.HistoryRound) == 1
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUsing then
      data.additionalDamage = (data.additionalDamage or 0) + 1
      if player:getMark("lingling__tingzhen1") == 0 then
        room:setPlayerMark(player, "lingling__tingzhen1", 1)
        if #room.logic:getEventsOfScope(GameEvent.UseCard, 2, function (e)
          local use = e.data[1]
          return use.from == player.id and use.card.trueName == "slash"
        end, Player.HistoryGame) == 1 then
          data.additionalDamage = data.additionalDamage + 1
        end
      end
    elseif event == fk.CardUseFinished then
      room:addPlayerMark(player, MarkEnum.SlashResidue.."-round", 1)
      player:drawCards(2, self.name)
      if player:getMark("lingling__tingzhen2") == 0 and not player.dead then
        room:setPlayerMark(player, "lingling__tingzhen2", 1)
        if #room.logic:getEventsOfScope(GameEvent.UseCard, 2, function (e)
          local use = e.data[1]
          return use.from == player.id and use.card.type == Card.TypeTrick
        end, Player.HistoryGame) == 1 then
          player:drawCards(2, self.name)
        end
      end
    end
  end,
}
local bizou = fk.CreateActiveSkill{
  name = "lingling__bizou",
  anim_type = "control",
  card_num = 0,
  target_num = 0,
  prompt = "#lingling__bizou",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local roundCount = room:getTag("RoundCount")
    roundCount = roundCount + 1
    room:setTag("RoundCount",  roundCount)
    room:doBroadcastNotify("UpdateRoundNum", roundCount)
    room:loseHp(player, 1, self.name)
    if player.dead then return end
    player:setCardUseHistory("", 0, Player.HistoryRound)
    local targets = table.filter(room.alive_players, function (p)
      return player:getNextAlive() == p or player:getLastAlive() == p
    end)
    local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1,
      "#lingling__bizou-choose", self.name, true)
    if #to > 0 then
      to = room:getPlayerById(to[1])
      room:setPlayerMark(to, MarkEnum.PlayerRemoved.."-turn", 1)
      room:setPlayerMark(to, "@@lingling__bizou-turn", 1)
    end
  end,
}
local bizou_prohibit = fk.CreateProhibitSkill{
  name = "#lingling__bizou_prohibit",
  prohibit_use = function(self, player, card)
    return card and player:getMark("@@lingling__bizou-turn") ~= 0
  end,
  is_prohibited = function(self, from, to, card)
    return card and to:getMark("@@lingling__bizou-turn") ~= 0
  end,
}
local bizou_trigger = fk.CreateTriggerSkill{
  name = "#lingling__bizou_trigger",

  refresh_events = {fk.PreHpRecover, fk.PreHpLost, fk.DamageInflicted},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:getMark("@@lingling__bizou-turn") ~= 0
  end,
  on_refresh = function(self, event, target, player, data)
    if event == fk.DamageInflicted then
      data.damage = 0
    else
      data.num = 0
    end
  end,
}
local weiyuan = fk.CreateTriggerSkill{
  name = "lingling__weiyuan",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = #table.filter(room.alive_players, function (p)
      return table.find(p:getCardIds("h"), function (id)
        return Fk:getCardById(id).trueName == "jink"
      end)
    end)
    if n > 0 then
      room:changeShield(player, n)
    end
  end,
}
bizou:addRelatedSkill(bizou_prohibit)
bizou:addRelatedSkill(bizou_trigger)
zhengchenggong:addSkill(tingzhen)
zhengchenggong:addSkill(bizou)
zhengchenggong:addSkill(weiyuan)
Fk:loadTranslationTable{
  ["lingling__zhengchenggong"] = "郑成功",
  ["#lingling__zhengchenggong"] = "国姓爷",
  ["designer:lingling__zhengchenggong"] = "伶",
  ["illustrator:lingling__zhengchenggong"] = "珊瑚虫",

  ["lingling__tingzhen"] = "廷震",
  [":lingling__tingzhen"] = "奇数轮内，本轮你使用首张【杀】伤害+1，若为本局游戏首次使用【杀】则再+1。偶数轮内，本轮你使用首张锦囊牌后，"..
  "你摸两张牌且使用【杀】的次数上限+1，若为本局游戏首次使用锦囊牌则再摸两张牌。",
  ["lingling__bizou"] = "避走",
  [":lingling__bizou"] = "出牌阶段限一次，你可以失去1点体力令轮次数+1，本轮你视为未使用牌，然后你可以将一名邻家调离至回合结束。",
  ["lingling__weiyuan"] = "威远",
  [":lingling__weiyuan"] = "游戏开始时，你获得X点护甲（X为手牌中有【闪】的角色数），至多获得4点。"..
  "<br><br> <font color = '#a40000'>孤臣秉孤忠，浩气磅礴留千古；<br>正人扶正气，莫教成败论英雄。",
  ["#lingling__bizou"] = "避走：你可以失去1点体力令轮次数+1，然后可以调离一名邻家",
  ["#lingling__bizou-choose"] = "避走：你可以调离一名邻家至回合结束",
  ["@@lingling__bizou-turn"] = "被调离",
}

return extension
